<script setup lang="ts">
import {computed, onMounted, ref, watch} from "vue";

const rotateX = ref(0);
const rotateY = ref(0);
const previewImage = ref<HTMLImageElement | null>(null);
const tools = ref<HTMLDivElement | null>(null);
const isPin = ref(true);
const opacity = ref(1.0);
watch(opacity, (value) => {
    setTimeout(() => {
        // @ts-ignore
        window.modifyOpacity(value)
    }, 0);
})

const bodyStyle = computed(() => {
    return {
        transform: `rotateX(${rotateX.value}deg) rotateY(${rotateY.value}deg)`
    }
})
watch(bodyStyle, (value) => {
    for (let key in value) {
        // @ts-ignore
        document.body.style[key as any] = value[key];
    }
})

let lock = false;

const doRotate = (degree: number) => {
    // console.log('doRotate', degree);
    if (lock) {
        return;
    }
    lock = true;
    const width = previewImage.value?.width as number;
    const height = previewImage.value?.height as number;
    //计算改变后窗口位置和大小
    let R = Math.sqrt(width * width + height * height);
    let xOffset = (R - width) / 2;
    let yOffset = (R - height) / 2;
    // console.log(R, 'xOffset', xOffset, 'yOffset', yOffset);
    previewImage.value?.addEventListener('load', () => {
        // @ts-ignore
        window.moveBounds(yOffset - xOffset, xOffset - yOffset, height, width);
        lock = false;
    }, {once: true});
    previewImage.value?.setAttribute('src', rotateImage(degree));
}


function rotateImage(degree: number) {
    degree = degree % 360;
    let tmpImg = new Image()
    tmpImg.src = previewImage.value?.src as string;
    let canvas = document.createElement('canvas');
    let context = canvas.getContext('2d');
    let height = tmpImg.height;
    let width = tmpImg.width;
    canvas.width = height;
    canvas.height = width;
    context?.translate(canvas.width / 2, canvas.height / 2);
    context?.rotate(degree * Math.PI / 180);
    context?.drawImage(tmpImg, -width / 2, -height / 2);
    return canvas.toDataURL();
}

onMounted(() => {
    let keyCounter = {
        lastKey: undefined as undefined | string,
        key: undefined as undefined | string,
        count: 3,
        time: 0
    }
    let controlKey = {} as any;
    document.addEventListener("keyup", event => {
        delete controlKey[event.key]
    })
    document.addEventListener("keydown", event => {
        // console.log('event.key', event.key);
        //长按操作将加速
        if (keyCounter.key === event.key && new Date().getTime() - keyCounter.time < 200) {
            keyCounter.count++
        } else {
            keyCounter.key = event.key
            keyCounter.count = 3;
            keyCounter.time = 0;
        }
        keyCounter.time = new Date().getTime();
        switch (event.key) {
            case "c":
            case "C":
                if (controlKey["Control"] || controlKey["Meta"]) {
                    document.body.className = ""
                    // @ts-ignore
                    setTimeout(() => window.copyImage(), 1000)
                    event.preventDefault()
                }
                break
            case "s":
            case "S":
                if (controlKey["Control"] || controlKey["Meta"]) {
                    document.body.className = ""
                    // @ts-ignore
                    setTimeout(() => window.saveImage(), 1000)
                    event.preventDefault()
                }
                break
            case "Escape":
                doClose()
                break;
            case "ArrowUp":
                // @ts-ignore
                window.moveBounds(0, -keyCounter.count / 3);
                event.preventDefault()
                break;
            case "ArrowDown":
                // @ts-ignore
                window.moveBounds(0, keyCounter.count / 3);
                event.preventDefault()
                break;
            case "ArrowLeft":
                // @ts-ignore
                window.moveBounds(-keyCounter.count / 3, 0);
                event.preventDefault()
                break;
            case "ArrowRight":
                // @ts-ignore
                window.moveBounds(keyCounter.count / 3, 0);
                event.preventDefault()
                break;
            case "+":
            case "=":
                // console.log('keyCounter.count', keyCounter.count / 2, previewImage.value?.height as number / previewImage.value?.width as number);
                // @ts-ignore
                window.resize(keyCounter.count / 2, previewImage.value?.height as number / previewImage.value?.width as number);
                event.preventDefault()
                break;
            case "-":
            case "_":
                // console.log('keyCounter.count', previewImage.value?.width);
                if (previewImage.value?.width as number > 130) {
                    // @ts-ignore
                    window.resize(0 - keyCounter.count / 2, previewImage.value?.height as number / previewImage.value?.width as number);
                    event.preventDefault()
                }
                break;
            case "【":
            case "[": {
                doRotate(-90);
                event.preventDefault()
                break;
            }
            case "】":
            case "]": {
                doRotate(90);
                event.preventDefault()
                break;
            }
            //左右反转
            case "Home":
            case "End":
                rotateY.value += 180;
                event.preventDefault()
                break;
            //上下反转
            case "PageUp":
            case "PageDown":
                rotateX.value += 180;
                event.preventDefault()
                break;
            case ",":
                if (controlKey["Control"] || controlKey["Meta"]) {
                    opacity.value = Math.max(opacity.value - 0.1, 0.1);
                    // @ts-ignore
                    window.modifyOpacity(opacity.value);
                    event.preventDefault()
                }
                break
            case ".":
                if (controlKey["Control"] || controlKey["Meta"]) {
                    opacity.value = Math.min(opacity.value + 0.1, 1);
                    // @ts-ignore
                    window.modifyOpacity(opacity.value);
                    event.preventDefault()
                }
                break;
        }
        controlKey[event.key] = true
    });
    document.addEventListener("wheel", (e) => {
        // @ts-ignore
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        if (delta < 0 && previewImage.value?.width as number <= 100) {
            return false;
        }
        console.log('delta', delta);
        //     // @ts-ignore
        //     window.resize(delta * 7, previewImage.value?.height as number / previewImage.value?.width as number);
        //     return false;
    }, false);
    document.addEventListener('pinChange', (event: any) => {
        isPin.value = event.detail
    });
});
const doPin = () => {
    // @ts-ignore
    window.triggerPin();
}
const doClose = () => {
    window.close();
}
const opacityFormat = (value: number) => {
    return `${Math.round(value * 100)}%`;
}
const onMouseMove = () => {
    if (document.body.classList.contains('body-focus')) {
        return
    }
    document.body.classList.add('body-focus');
}
</script>


<template>
    <div @mousemove="onMouseMove">
        <img ref="previewImage" id="preview" draggable="false"/>
        <div ref="tools" class="tools">
            <a href="javascript:;" class="item btn bg-white bg-opacity-50"
               @click="doPin"
               :class="isPin?'active':''">
                <icon-pushpin/>
            </a>
            <div class="item wide bg-white bg-opacity-50 px-3 rounded-lg">
                <a-slider v-model="opacity"
                          :default-value="1"
                          :style="{ width: '50px' }"
                          :step="0.05"
                          :min="0.1"
                          :format-tooltip="opacityFormat"
                          :max="1"/>
            </div>
            <div class="item-space"></div>
            <a href="javascript:;" class="item btn bg-white bg-opacity-50"
               @click="doClose">
                <icon-close/>
            </a>
        </div>
        <div class="drag-area"></div>
    </div>
</template>
